package example;

import java.io.IOException;
import java.util.stream.Stream;

import de.siegmar.fastcsv.reader.CsvReader;
import de.siegmar.fastcsv.reader.NamedCsvRecord;

/// Example for reading CSV data with a mapping function.
public class ExampleCsvReaderMapping {

private static final String DATA = 
    "ID,firstName,lastName\n" +
    "1,John,Doe\n" +
    "2,Jane,Smith\n";

    public static void main(final String[] args) throws IOException {
        try (Stream<Person> persons = readPersons()) {
            persons.forEach(System.out::println);
        }
    }

    private static Stream<Person> readPersons() throws IOException {
        try (CsvReader<NamedCsvRecord> csv = CsvReader.builder().ofNamedCsvRecord(DATA)) {
            return csv.stream().map(ExampleCsvReaderMapping::mapPerson);
        }
    }

    private static Person mapPerson(final NamedCsvRecord rec) {
        return new Person(
            Long.parseLong(rec.getField("ID")),
            rec.getField("firstName"),
            rec.getField("lastName")
        );
    }

    static class Person {
        private long id;
        private String firstName;
        private String lastName;

        Person(long id, String firstName, String lastName){
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", firstName='" + firstName + '\'' +
                    ", lastName='" + lastName + '\'' +
                    '}';
        }

        public String getFirstName() {
            return firstName;
        }
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
        public long getId() {
            return id;
        }
        public void setId(long id) {
            this.id = id;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }

}
